package com.situ.system.projects.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.situ.system.performance.model.PerformanceModel;
import com.situ.system.util.JDBCUtil;

public class ProjectsDao {

	private Connection connection = null;
	private PreparedStatement ps = null;

	// 增加
	public String insert(PerformanceModel model) {
		String sql = "insert into performance(e_id, p_id, p_score) value(?,?,?)";
		return "" + JDBCUtil.shuai(sql, model.getE_id(), model.getP_id(), model.getP_score());
	}

	// 删除
	public String delete(PerformanceModel model) {
		String sql = "delete from performance where e_id = ?";
		return "" + JDBCUtil.shuai(sql, model.getE_id());
	}

	// 只能更新某个人的绩效值
	public String updata(PerformanceModel model) {
		String sql = "update performance set p_score = ? where e_id = ? ";
		return "" + JDBCUtil.shuai(sql, model.getP_score(), model.getE_id());
	}

	// 查询
	public List<PerformanceModel> select(PerformanceModel model) {
		StringBuffer sql = new StringBuffer("select e_id, p_id, p_score from performance where 1=1");
		List<Object> list = new ArrayList<Object>();
		list = where(sql, model);
		List<PerformanceModel> list2 = new ArrayList<PerformanceModel>();
		ResultSet set = null;
		try {
			connection = JDBCUtil.getConnection();
			ps = connection.prepareStatement(sql.toString());
			for (int i = 0; i < list.size(); i++) {
				ps.setObject(i + 1, list.get(i));
			}
			set = ps.executeQuery();
			while (set.next()) {
				PerformanceModel model1 = new PerformanceModel();
				model1.setE_id(set.getString("e_id"));
				model1.setP_id(set.getString("p_id"));
				model1.setP_score(set.getString("p_score"));
				list2.add(model1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, ps);
		}
		return list2;
	}

	public Integer selectCount(PerformanceModel model) {
		StringBuffer sql = new StringBuffer("select count(1) from performance");
		ResultSet rs = null;
		try {
			connection = JDBCUtil.getConnection();
			ps = connection.prepareStatement(sql.toString());
			rs = ps.executeQuery();
			if (rs.next()) {
				System.out.println(rs.getInt(1));
				return rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, ps);
		}
		return null;
	}

	// 绩效查询的话 应该只有按员工的编号查吧
	public List<Object> where(StringBuffer sql, PerformanceModel model) {
		String s_id = model.getE_id();
		List<Object> list = new ArrayList<Object>();
		if (s_id != null && !s_id.trim().isEmpty()) {
			sql.append(" and e_id like ?");
			list.add(s_id);
		}
		if (model.isPageOn()) {
			sql.append(" limit ?,? ");
			list.add(model.getRowStart());
			list.add(model.getPageLimit());
		}
		return list;
	}
}
